<template>
    <div>
        <v-app-bar app elevation="0" dense>
            <v-toolbar-title class="text-center flex-grow-1 subtitle-1">{{title}}</v-toolbar-title>
        </v-app-bar>

        <v-container fluid>
             <v-row dense v-if="items.length > 0" no-gutters>
                <v-col cols="12" v-if="!finished">
                    <v-btn :ripple="false" plain text block @click="loadMore" :loading="loading" class="text--disabled">加载历史消息</v-btn>
                </v-col>
            </v-row>

            <template v-for="msg of items">
                <v-row  :key="msg.id" dense v-if="msg.sender_id != uid">
                    <v-col cols="auto" >
                        <v-avatar
                            color="primary"
                            rounded
                            size="36"
                        >
                            <span class="white--text subtitle-1">{{msg.sender.substr(0,1)}}</span>
                        </v-avatar>
                    </v-col>
                    <v-col>
                        <div class="body-2 text--disabled">{{msg.sender}} {{msg.created_at}}</div>
                        <span class="body-1 white pa-2 rounded-lg font-weight-regular speech-bubble arrow-left">{{msg.msg}}</span>
                    </v-col>
                </v-row>

                <v-row  dense v-else :key="msg.id">
                    <v-col class="text-right">
                        <span class="body-1 pa-2 rounded-lg green font-weight-regular speech-bubble arrow-right">{{msg.msg}}</span>
                    </v-col>
                    <v-col cols="auto" >
                        <v-avatar
                            rounded
                            color="green"
                            dar
                            size="36"
                        >
                            <span class="black--text subtitle-1">{{msg.sender.substr(0,1)}}</span>
                        </v-avatar>
                    </v-col>
                </v-row>
            </template>
            <v-row id="chat-bottom"></v-row>
        </v-container>
        <v-footer
            app
            height="72"
            inset
            color="white"
        >
            <v-text-field
                dense
                flat
                hide-details
                outlined
                rounded
                v-model="msg"
                placeholder="请输入"
            >
                <template v-slot:append-outer>
                    <v-btn
                        v-if="uid"
                        color="primary"
                        class="mt-n2"
                        depressed
                        @click="sendMsg"
                        :loading="sending">发送
                    </v-btn>
                </template>
            </v-text-field>
        </v-footer>
    </div>
</template>

<script>
import axios from "axios";
import { mapGetters } from 'vuex';

export default {
    data: () => ({
        title: '在线客服',
        msg: '',
        sending: false,
        items: [],
        loading: false,
        pageNo: 1,
        pageSize: 20,
        finished: false,
        id: 0,
        channel: null
    }),

    computed: {
        ...mapGetters([
            'uid',
            'token',
            'inchat'
        ]),
    },

    created() {
        this.id = this.$route.params.id;
        this.init()
    },

    beforeRouteUpdate(to, from, next) {
        this.id = to.params.id;
        next();
        this.init();
    },

    beforeDestroy() {

    },
    methods: {

        init() {
            const that = this;

            if(that.channel) {
                that.channel.stopListening(`.room.msg.new`, that.onNewMsg);
            }
            that.items = [];
            that.finished = false;
            that.pageNo = 1;
            that.load();


            that.channel =  window.Echo.private(`room.${that.id}`);
            that.channel.listen('.room.msg.new', that.onNewMsg);
        },

        onNewMsg(data) {
            const that = this;
            that.items.push(data);
            that.$nextTick(() => {
                that.$vuetify.goTo('#chat-bottom');
            });
        },

        load() {
            const that = this;
            that.loading = true;
            axios.get(`/chat/room/msg`,{ params: {
                pageSize: this.pageSize,
                page: this.pageNo,
                room_id: this.id
            }}).then((response) => {
                if (response.data.code == 0) {
                    that.title = response.data.data.title;

                    response.data.data.items.forEach(v => {
                        that.items.unshift(v);
                    })

                    if (response.data.data.items.length < that.pageSize) {
                        that.finished = true;
                    }

                    if (that.pageNo == 1) {
                        that.$nextTick(() => {
                           that.inchat && that.$vuetify.goTo('#chat-bottom');
                        });
                    }

                } else {
                    that.$toast.open({
                        message: response.data.msg,
                        type: 'error',
                        position: 'top-right',
                    });
                }
            })
            .catch(function () {})
            .then(function () {
                 that.loading = false;
            });
        },
        loadMore() {
            this.pageNo++;
            this.load();
        },

        sendMsg() {
            if(this.msg.length <= 0) return;

            const that = this;
            that.sending = true;
            axios.post(`/chat/room/msg`, {
                msg: this.msg,
                room_id: this.id
            }).then(response => {
                if (response.data.code === 0) {
                    that.msg = '';
                    that.$vuetify.goTo('#chat-bottom');
                } else {
                    that.$toast.open({
                        message: response.data.msg,
                        type: 'error',
                        position: 'top-right',
                    });
                }
            })
            .catch(function () {})
            .then(function () {
                that.sending = false;
            });
        }
    },
};
</script>

<style lang="scss" scoped>

.speech-bubble {
    position: relative;
    display: inline-block;

    &.arrow-left::before {
        content: "";
        position: absolute;
        left: -4px;
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
        border-right: 4px solid #000;
        border-right-color: inherit;
    }

    &.arrow-right::after {
        content: "";
        position: absolute;
        right: -4px;
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
        border-right: 4px solid #000;
        border-right-color: inherit;
        transform: rotate(180deg);
    }
}




</style>
